open Card;;
open Hand;;
open Common;;

type status = 
  | Big_blind
  | Small_blind
  | None;;

type action = 
  | Call
  | Raise of int
  | Fold
  | Check ;;

type player = {
  name : string;
  mutable chips     : int;
  mutable hand      : card list;
  mutable position  : status;
  mutable dealer    : bool;
  mutable last_bet  : int;
  mutable last_move : action};;


      
let string_of_action a = 
  match a with 
    | Call    -> "Call"
    | Raise n -> "Raise to "^string_of_int n^"\n"
    | Fold    -> "Fold"
    | Check   -> "Check";;


let find_winner players = 
  let compare_p_h_tuple (p1,h1) (p2,h2) = compare_hands h1 h2 in
  let rec convert l = 
    match l with
      | h::t -> (h, (Hand.create_hand h.hand))::(convert t)
      | [] -> [] in
  let cp = convert players in
  let scp = List.sort compare_p_h_tuple cp  in
    List.hd scp;;

type players = player list;;


let add_card player card = 
  player.hand <- card::player.hand;;

let rm_card player = 
  let np  = player in
    np.hand <- [];
    np;;

let make_player name = 
  {name = name; chips = 1500; hand =[]; position = None;dealer = false; last_bet = 0; last_move = Fold};;


let play current_bet player  = 
  print_line();
  print_string ("That's your turn "^player.name^" !\n");
  print_string "You have ";
  print_int player.chips;
  print_string " chips\n";
  print_string "Your hand is "; 
  print_card_list player.hand;
  let res = ref (-1) in
    while ((!res) < 1 )||( (!res) > 4)
    do
      print_string "What do you want to do?\n";
      print_string "1-Fold\n";
      print_string "2-Check\n";
      print_string "3-Call\n";
      print_string "4-Raise\n";
      res := read_int();
      if ( ( (!res = 3 ) || (!res = 4) ) & ( player.chips < current_bet ) )
	   
      then ( print_string "You dont have enougth chips!\n"; res := 0   )
      else if ((!res = 2) &( current_bet > 0))
      then (
	print_string "You can do that some player already betted!\n";
	res := 0
      )
    done;
    match !res with
      | 1 -> player.last_move <- Fold ;Fold
      | 2 -> player.last_move <- Check ;Check
      | 3 -> player.chips <- (player.chips - current_bet);player.last_move <- Call ; Call
      | 4 -> 
	  (  
            
	    print_string "Which amout want you bet? \n";
            res := (try read_int () with Failure "int_of_string" -> -1);
                
	     while (!res < current_bet) & (!res > player.chips)
	     do
	       print_string "Don't be dumb give me a real bet \n";
                res := (try read_int () with Failure "int_of_string" -> -1)
	     done;
	     player.chips <- (player.chips - !res); 
	     player.last_move <- Raise (!res );
	     player.last_bet <- (!res);
	     Raise (!res )
	  )
      | _ -> failwith "Table.play : Unexpected value";;
